﻿using System;
using System.Web.UI.WebControls;

namespace MyOrganizer.Pages
{
    public partial class Books : System.Web.UI.Page
    {
        private MyOrganizerModel.BusinessModel Bl = null;
        private MyOrganizerModel.Database.Books Book = null;
        private int UserId { get { return Int32.Parse(Session["UserId"].ToString()); } }

        protected void Page_Load(object sender, EventArgs e)
        {
            Bl = MyOrganizerModel.BusinessModel.GetInstance;
            LoadData();
        }

        protected void lnkAdd_Click(object sender, EventArgs e)
        {
            TextBox txt = default(TextBox);
            foreach (var ctrl in pnlPopUp.Controls)
            {
                if (object.ReferenceEquals(ctrl.GetType(), typeof(TextBox)))
                {
                    txt = (TextBox)ctrl;
                    txt.Text = String.Empty;
                }
            }
            mdlPopUp.Show();
        }

        protected void lnkSave_Click(object sender, EventArgs e)
        {
            Book = new MyOrganizerModel.Database.Books();
            if (txtId.Text.Equals(string.Empty))
            {
                Book.UserId = UserId;
                Book.Name = txtName.Text;
                Book.Type = txtType.Text;
                Book.Completed = chkCompleted.Checked;
                Bl.AddBook(Book);
            }
            else
            {
                Book.BookId = Int32.Parse(txtId.Text);
                Book.UserId = UserId;
                Book.Name = txtName.Text;
                Book.Type = txtType.Text;
                Book.Completed = chkCompleted.Checked;
                Bl.UpdateBook(Book);
            }
            LoadData();
        }

        protected void rptData_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            switch (e.CommandName.ToString())
            {
                case "Edit":
                    Book = Bl.GetBookByBookId(Int32.Parse(e.CommandArgument.ToString()));
                    txtId.Text = Book.BookId.ToString();
                    txtName.Text = Book.Name;
                    txtType.Text = Book.Type;
                    chkCompleted.Checked = (bool)Book.Completed;
                    mdlPopUp.Show();
                    break;

                case "Delete":
                    Bl.DeleteBook(Int32.Parse(e.CommandArgument.ToString()));
                    LoadData();
                    break;

                default:
                    break;
            }
        }

        private void LoadData()
        {
            rptData.DataSource = Bl.GetBooks();
            rptData.DataBind();
        }
    }
}